import { fileURLToPath, URL } from "node:url"
import { resolve } from "path"

import { defineConfig, loadEnv } from "vite"
import vue from "@vitejs/plugin-vue"
import vueJsx from "@vitejs/plugin-vue-jsx"

import CreateComponents from "./extend/component"
import CreateTraversalIcons from "./extend/traversalIcons"

import AutoImport from "unplugin-auto-import/vite"

// https://vitejs.dev/config/
export default ({ mode }) => {
	const { VITE_APP_SERVICE_URL, VITE_APP_SERVICE_URL_CODE } = loadEnv(mode, process.cwd())

	return defineConfig({
		base: "/",
		plugins: [
			vue(),
			vueJsx(),
			CreateComponents(),
			CreateTraversalIcons(),
			AutoImport({
				imports: [
					"vue",
					"vue-router",
					{
						"/axios": ["getAxios", "postAxios", "putAxios", "deleteAxios"],
					},
				],
			}),
		],
		resolve: {
			alias: {
				"@": fileURLToPath(new URL("./src", import.meta.url)),
				"/axios": resolve(__dirname, "src/axios"),
				"/store": resolve(__dirname, "src/store"),
				"/config": resolve(__dirname, "src/config"),
				"/plugins": resolve(__dirname, "src/plugins"),
				"/utils": resolve(__dirname, "src/utils"),
				"/basis": resolve(__dirname, "src/mixins/basis"),
				"/mixins": resolve(__dirname, "src/mixins"),
				"/add": resolve(__dirname, "src/mixins/add"),
				"/edit": resolve(__dirname, "src/mixins/edit"),
				"/info": resolve(__dirname, "src/mixins/info"),
				"/packages": resolve(__dirname, "src/packages"),
				"/style": resolve(__dirname, "src/assets/style"),
				"/composables": resolve(__dirname, "src/composables"),
			},
		},
		build: {
			rollupOptions: {
				output: {
					// 打包时分包逻辑
					manualChunks: {
						"echarts": ["echarts"],
						"element-plus": ["element-plus"],
					},
				},
			},
		},
		server: {
			host: "0.0.0.0",
			port: 3000,
			proxy: {
				"/api/": {
					target: VITE_APP_SERVICE_URL,
					changeOrigin: true,
					ws: true,
					rewrite: path => path.replace(/^\/api/, ""),
					// rewrite: path => path,
				},
				"/code/": {
					target: VITE_APP_SERVICE_URL_CODE,
					changeOrigin: true,
					ws: true,
					rewrite: path => path.replace(/^\/code/, ""),
				},
			},
		},
	})
}
